package com.fare.taluo.action.crawl.line;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.List;

import javax.inject.Inject;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;

import com.fare.taluo.action.crawl.excel.CrawlLineExcelImport;
import com.fare.taluo.application.crawl.TaskTemplateApplication;
import com.fare.taluo.base.struts2.json.BaseJsonStrutsAction;
import com.fare.taluo.base.struts2.json.JsonReturnBean;
import com.fare.taluo.conf.system.DefaultPropertiesLoader;
import com.fare.taluo.io.excel.ExcelImportException;
import com.fare.taluo.vo.crawl.CrawlLineVO;
/**
 * 抓取航线配置导入
 * @author xiangsf 2013-6-4
 *
 */
@Namespace("/crawl/line/lineimport")
public class LineImportAction extends BaseJsonStrutsAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = -1814256390260877202L;
	
	@Inject
	private TaskTemplateApplication taskTemplateApplication;
	
	private String excelFileName;
	
	private File uploadFile;
	
	private InputStream excelFileStream;
	
	
	public String getExcelFileName() {
		return excelFileName;
	}

	public InputStream getExcelFileStream() {
		return excelFileStream;
	}

	public void setUploadFile(File uploadFile) {
		this.uploadFile = uploadFile;
	}

	@Action(value="excelTemplate",results={@Result(name="success", type="stream",
			params={"contentType","application/vnd.ms-excel",
			"contentCharSet", "UTF-8",
			"inputName","excelFileStream",
	    	"contentDisposition","attachment;filename=${excelFileName}.xls",  
	    	"bufferSize","1024" })})
	public String excelTemplate() throws Exception{
		excelFileName = java.net.URLEncoder.encode("CrawlLineTemplate", "UTF-8");
		File downFile = new File(DefaultPropertiesLoader.getAppExcelFilePath()+"/CRAWL_LINE_IMPORT_TEMPLATE.xls");
		excelFileStream = new FileInputStream(downFile);
		return SUCCESS;
	}
	
	
	@Action(value="excelImport",interceptorRefs = @InterceptorRef(value = "fileUploadStack"),
			results={@Result(name="success", type="json", params={"root","returnBean"})})
	public String excelImport() throws Exception{
		List<CrawlLineVO> lines = null;
		try{
			returnBean = new JsonReturnBean();
			lines = (List<CrawlLineVO>)new CrawlLineExcelImport().readExcel(uploadFile);
			if(lines != null) taskTemplateApplication.importTasks(lines);
			returnBean.setHasOk(true);
		}catch(ExcelImportException e){
			e.printStackTrace();
			logger.error(e);
			returnBean.setHasOk(false);
			returnBean.setTip(JsonReturnBean.TIP_FAIL);
			returnBean.setBean(e.getMessage());
		}catch(Exception e){
			e.printStackTrace();
			logger.error(e);
			returnBean.setHasOk(false);
			returnBean.setTip(JsonReturnBean.TIP_ERROR);
			returnBean.setBean(e.getMessage());
		}finally{
			
		}
		return SUCCESS;
	}
}
